package com.wantup.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/25 15:44
 * <p>
 * 解决线程安全的问题：
 * synchronize  隐式的锁
 * 1. 同步代码块
 * 2. 同步方法
 * <p>
 * jdk1.5以后 显示的锁
 * 3. 同步锁Lock 是一个显示锁 需要通过lock()方法上锁 必须通过unLock()方法释放锁。
 */
public class TestLock {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket, "一号窗口").start();
        new Thread(ticket, "二号窗口").start();
        new Thread(ticket, "三号窗口").start();

    }

}


class Ticket implements Runnable {

    /**
     * 共享资源
     */
    private int ticket = 10;
    private Lock lock = new ReentrantLock();


    @Override
    public void run() {

        while (true) {
            try {

                lock.lock();
                if (ticket > 0) {

                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "   完成售票,余票为 : " + (--ticket));
                }

            } finally {
                //释放锁
                lock.unlock();
            }
        }

    }
}


